package com.woniu.project.sentinel.exception;

import com.woniu.project.core.exception.ErrorResult;
import com.woniu.project.core.exception.ProjectExceptionCode;
import lombok.extern.slf4j.Slf4j;

import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 处理404异常以及其他框架内部异常
 * @Author: Klaus
 * @Date: 2020/9/27 21:37
 */
@RestController
@Slf4j
public class GloableNoUrlExceptionHandler implements ErrorController {

    private final ErrorAttributes errorAttributes;

    public GloableNoUrlExceptionHandler(ErrorAttributes errorAttributes) {
        this.errorAttributes = errorAttributes;
    }

    //此方法为实现ErrorController接口重写的方法
    //出现异常之后会调用这个方法 返回出现异常之后执行的逻辑
    @Override
    public String getErrorPath() {
        return "/error";
    }


    @GetMapping("/error")
    public ResponseEntity<ErrorResult> exceptionHandler(HttpServletRequest request){
        ServletWebRequest swr = new ServletWebRequest(request);
        Map<String,Object> maps = errorAttributes.getErrorAttributes(swr,true);
        ErrorResult errorResult = new ErrorResult();
        if(maps.get( "status" ).equals(404)) {
            errorResult = new ErrorResult();
            errorResult.setCode(ProjectExceptionCode.SYS_URL_NOT.getCode());
            errorResult.setMsg("找不到资源:"+maps.get("path").toString());
            log.error("出现异常:code:{},message:{},class:{}" ,404,"找不到资源:"+maps.get("path").toString());
            ResponseEntity<ErrorResult> resp = new ResponseEntity<>(errorResult,HttpStatus.NOT_FOUND);
            return resp;
        }
        errorResult = new ErrorResult();
        errorResult.setCode(500);
        errorResult.setMsg(maps.get("path").toString());
        log.error("出现异常:code:{},message:{},class:{}" ,500,"找不到资源:"+maps.get("path").toString());
        ResponseEntity<ErrorResult> resp = new ResponseEntity<>(errorResult,HttpStatus.INTERNAL_SERVER_ERROR);
        return resp;
    }
    //得到堆栈信息的字符串
    private String getstackTrace(Exception e) {
        StringBuffer sbs = new StringBuffer();
        for(StackTraceElement st : e.getStackTrace()) {
            sbs.append(st.toString()).append( "\r\n");
        }
        return sbs.toString();
    }
}
